<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height: 60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="showDialog = true"
                >新增角色</el-button
              >
            </el-row>
            <!-- 给表格绑定数据 -->
            <el-table border="" :data="list">
              <el-table-column
                type="index"
                label="序号"
                width="120"
                align="center"
              />
              <el-table-column
                prop="name"
                label="角色名称"
                width="240"
                align="center"
              />
              <el-table-column prop="description" label="描述" align="center" />
              <el-table-column label="操作" align="center">
                <!-- 作用域插槽 -->
                <template v-slot="{ row }">
                  <el-button
                    size="small"
                    type="success"
                    @click="assignRole(row.id)"
                    >分配权限</el-button
                  >
                  <el-button
                    size="small"
                    type="primary"
                    @click="editRole(row.id)"
                    >编辑</el-button
                  >
                  <el-button
                    size="small"
                    type="danger"
                    @click="deleteRole(row.id)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-row
              type="flex"
              justify="center"
              align="middle"
              style="height: 60px"
            >
              <!-- 分页组件 -->
              <el-pagination
                :current-page="page.page"
                layout="prev,pager,next"
                :total="page.total"
                :page-size="page.pagesize"
                @current-change="changePage"
              />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form label-width="120px" style="margin-top: 50px">
              <el-form-item label="公司名称">
                <el-input
                  v-model="formData.name"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input
                  disabled
                  style="width: 400px"
                  v-model="formData.companyAddress"
                />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input
                  disabled
                  style="width: 400px"
                  v-model="formData.mailbox"
                />
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  type="textarea"
                  :rows="3"
                  disabled
                  style="width: 400px"
                  v-model="formData.remarks"
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <!-- 放置一个弹层组件 -->
    <el-dialog title="编辑弹层" :visible="showDialog" @close="btnCancel">
      <el-form
        ref="roleForm"
        :model="roleForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="roleForm.description" />
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <template v-slot:footer>
        <el-row type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="btnCancel">取消</el-button>
            <el-button size="small" type="primary" @click="btnOK"
              >确定</el-button
            >
          </el-col>
        </el-row>
      </template>
    </el-dialog>

    <!-- 分配权限弹出层 -->
    <el-dialog
      title="分配权限"
      :visible="showPermDialog"
      @close="btnPermCancel"
    >
    <!-- 
      check-strictly: 父子不关联
      check-strictly: 显示前面的复选框
      node-key里id作为唯一标识
      default-checked-keys默认展开所有key 的数组
     -->
      <el-tree
        ref="permTree"
        :data="permData"
        :props="defaultProps"
        default-expand-all=""
        show-checkbox
        :default-checked-keys="selectChecks"
        check-strictly
        node-key="id"
      />
      <!-- <template v-slot:footer> -->
      <el-row type="flex" justify="center" slot="footer">
        <el-col :span="6">
          <el-button type="primary" size="small" @click="btnPermOK"
            >确定</el-button
          >
          <el-button size="small" @click="btnPermCancel">取消</el-button>
        </el-col>
      </el-row>
      <!-- </template> -->
    </el-dialog>
  </div>
</template>

<script>
import {
  getRoleList,
  getCompanyInfo,
  deleteRole,
  getRoleDetail,
  updateRole,
  addRole,
  assignPerm,
} from "@/api/setting";
import { getPermissionList } from "@/api/permission";
import { mapGetters } from "vuex";
import { findChildren } from "@/utils";
export default {
  data() {
    return {
      // 默认勾选的节点的 key 的数组 用来接收当前角色所拥有的权限数据
      selectChecks: [],
      defaultProps: {
        label: "name",
      },
      // 专门来接收权限收集数据
      permData: [],
      // 记录当前点击分配权限的角色id
      roleId: null,
      showPermDialog: false,
      list: [], //承接数组
      page: {
        // 放置页面及相关数据
        page: 1,
        pagesize: 10,
        // 记录总数
        total: 0,
      },
      formData: {
        // 公司信息
      },
      showDialog: false,
      roleForm: {
        // name: "",
        // description : ""
      },
      rules: {
        name: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getRoleList(), this.getCompanyInfo();
  },
  methods: {
    async getRoleList() {
      const { total, rows } = await getRoleList(this.page);
      this.page.total = total;
      this.list = rows;
    },
    changePage(newPage) {
      // newPage 是当前点击的页码
      this.page.page = newPage;
      this.getRoleList();
    },
    async getCompanyInfo() {
      this.formData = await getCompanyInfo(this.companyId);
    },
    async deleteRole(id) {
      try {
        // 弹出框提示信息  在Dialog对话框里
        await this.$confirm("确认删除该角色吗");
        // 调用删除接口
        await deleteRole(id);
        // 重新加载数据
        this.getRoleList();
        // 提示删除成功信息
        this.$message.success("删除角色成功");
      } catch (error) {
        console.log(error);
      }
    },
    // 编辑功能
    async editRole(id) {
      // 实现数据回写
      this.roleForm = await getRoleDetail(id);
      this.showDialog = true;
    },
    // 新增功能
    async btnOK() {
      // try {
      //   await this.$refs.roleForm.validate();
      //   // roleForm有id就是编辑，没有就是新增
      //   if (this.roleForm.id) {
      //     await updateRole(this.roleForm);
      //   } else {
      //     // 新增业务
      //     await addRole(this.roleForm);
      //   }
      //   // 重新拉取数据
      //   this.getRoleList();
      //   this.$message.success("操作成功");
      //   this.showDialog = false;
      // } catch (error) {
      //   console.log(error);
      // }
      this.$refs.roleForm
        .validate()
        .then(() => {
          if (this.roleForm.id) {
            // 更新表单数据
            return updateRole(this.roleForm);
          }
          // 添加表单
          return addRole(this.roleForm);
        })
        .then(() => {
          this.getRoleList();
          this.$message.success("操作成功");
          this.showDialog = false;
          console.log(this.roleForm);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    btnCancel() {
      this.roleForm = {
        name: "",
        description: "",
      };
      // 移除校验
      this.$refs.roleForm.resetFields();
      this.showDialog = false;
    },
    // 分配权限功能  获取权限点数据
    async assignRole(id) {
      this.roleId = id;
      this.permData = findChildren(await getPermissionList(), "0");
      console.log(this.roleForm);
      // permIds当前角色所拥有的权限点数
      const { permIds } = await getRoleDetail(id);
      this.selectChecks = permIds;
      this.showPermDialog = true;
      console.log(this.selectChecks);
    },
    async btnPermOK() {
      await assignPerm({
        id: this.roleId,
        // getCheckedKeys:若节点可被选择（即 show-checkbox 为 true），则返回目前被选中的节点的 key 所组成的数组
        permIds: this.$refs.permTree.getCheckedKeys(),
      });
      this.$message.success("分配权限成功");
      this.showPermDialog = false;
    },
    btnPermCancel() {
      // 重置数据
      this.selectChecks = [];
      this.showPermDialog = false;
    },
  },
  computed: {
    ...mapGetters(["companyId"]),
  },
};
</script>

<style>
</style>
